/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package br.jm.acionista.relatorio;

import br.jm.acionista.entity.Cautela;
import br.jm.acionista.entity.RelatorioCertificadoTemp;
import br.jm.acionista.entity.TipoTransferencia;
import br.jm.acionista.filter.Conecta;
import br.jm.acionista.filter.Funcoes;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.fill.JRAbstractLRUVirtualizer;
import net.sf.jasperreports.engine.fill.JRGzipVirtualizer;

/**
 *
 * @author joao
 */
public class relatorio extends HttpServlet {

    private RelatorioCertificadoTemp[] selectedCertificadoCheck;
    private RelatorioCertificadoTemp selectedCertificadoTemp;
    private TipoTransferencia selectedTipoTransferencia;
    private Cautela selectedCautela;
    private Funcoes funcoes = new Funcoes();

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        ServletContext context = getServletContext();
        HttpSession session = request.getSession(false);

        Map parametros = new HashMap();

        String cWhere = "";
        String cOrder = "";
        String caminho = "/WEB-INF/relatorios/";
        String relatorio = "";

        String cTipRel = request.getParameter("tipRel");
        String tipAcionista = request.getParameter("tipAcionista");
        String tipFiltro = request.getParameter("tipFiltro");
        String filtro = request.getParameter("filtro");
        String order = request.getParameter("order");
        String orderTipo = request.getParameter("orderTipo");
        Map<String, String[]> cLista = request.getParameterMap();
        String cTipoTransf = request.getParameter("tipoTransf");

        String impPartic;
        String impProposta;
        String impObs;

        if (cTipRel.equals("acionista")) {
            relatorio = caminho.concat("acionista.jasper");

            tipAcionista = (String) session.getAttribute("tipAcionista");
            tipFiltro = (String) session.getAttribute("tipFiltro");
            filtro = (String) session.getAttribute("filtro");
            order = (String) session.getAttribute("order");

            if (!tipAcionista.equals("T")) {
                cWhere = "WHERE cliente.\"tip_cliente\" = '".concat(tipAcionista).concat("' ");
            }
            /*
             * if (!tipFiltro.equals("N")) { if (cWhere.contains("WHERE")) {
             * cWhere += " AND "; } else { cWhere += " WHERE "; } if
             * (tipFiltro.equals("C")) { cWhere += "cliente.\"num_cpf\" like
             * '%".concat(filtro).concat("%' "); } else { cWhere +=
             * "cliente.\"nom_cliente\" like '%".concat(filtro).concat("%' "); }
             * }
             *
             */

            //if (!order.equals("N")) {
            if (order.equals("C")) {
                cOrder = "ORDER BY cliente.\"num_cpf\" ";
            } else {
                cOrder = "ORDER BY cliente.\"nom_cliente\" ";
            }
            // }
        } else if (cTipRel.equals("livro")) {
            relatorio = caminho.concat("relatorio_livro.jasper");
            cWhere = "";
        } else if (cTipRel.equals("certificado")) {
            relatorio = caminho.concat("relatorio_certificado.jasper");
            cWhere = "";

            selectedCertificadoCheck = (RelatorioCertificadoTemp[]) session.getAttribute("tabAcionistas");
            cWhere = " where ";
            String cCondicao1 = " cliente.id_cliente in (";

            for (int i = 0; i < selectedCertificadoCheck.length; i++) {
                selectedCertificadoTemp = selectedCertificadoCheck[i];

                cCondicao1 = cCondicao1.concat(selectedCertificadoTemp.getIdCliente().toString().concat(","));
            }
            cCondicao1 = cCondicao1.concat("0) ");

            cWhere = cWhere.concat(cCondicao1);
        } else if (cTipRel.equals("certificadoComp")) {
            relatorio = caminho.concat("relatorio_Comp_Certificado.jasper");
            cWhere = "";

            selectedCertificadoCheck = (RelatorioCertificadoTemp[]) session.getAttribute("tabAcionistas");
            cWhere = " where ";
            String cCondicao1 = " cliente.id_cliente in (";

            for (int i = 0; i < selectedCertificadoCheck.length; i++) {
                selectedCertificadoTemp = selectedCertificadoCheck[i];

                cCondicao1 = cCondicao1.concat(selectedCertificadoTemp.getIdCliente().toString().concat(","));
            }
            cCondicao1 = cCondicao1.concat("0) ");

            cWhere = cWhere.concat(cCondicao1);

            if (order.equals("2")) {
                cOrder += "ORDER BY relatorio_certificado.\"dat_cautela\" ";
            } else {
                cOrder += "ORDER BY cliente.\"nom_cliente\" ";
            }
        } else if (cTipRel.equals("livroTransferencia")) {
            selectedCertificadoCheck = (RelatorioCertificadoTemp[]) session.getAttribute("tabAcionistas");
            String tipoVia = (String) session.getAttribute("tipovia");
            String cDatRel = (String) session.getAttribute("datRel");
            String cTransf = (String) session.getAttribute("transf");

            relatorio = caminho.concat("relatorio_livro_transferencia.jasper");
            cWhere = " where ";
            String cCondicao1 = null;

            if (tipoVia.equals("1")) {
                cCondicao1 = " cliente.id_cliente in (";

                for (int i = 0; i < selectedCertificadoCheck.length; i++) {
                    selectedCertificadoTemp = selectedCertificadoCheck[i];

                    cCondicao1 = cCondicao1.concat(selectedCertificadoTemp.getIdCliente().toString().concat(","));
                }
                cCondicao1 = cCondicao1.concat("0) ");
                cCondicao1 = cCondicao1.concat(" and cautela.dat_cautela = '").concat(cDatRel).concat("' ");
            } else {
                cCondicao1 = " cautela.num_transferencia in ".concat(cTransf);
            }

            cWhere = cWhere.concat(cCondicao1);
        } else if (cTipRel.equals("acionistaParticipacao")) {
            relatorio = caminho.concat("acionista_participacao.jasper");

            tipAcionista = (String) session.getAttribute("tipAcionista");
            orderTipo = (String) session.getAttribute("orderTipo");
            order = (String) session.getAttribute("order");

            cWhere = " WHERE cliente.qde_acao > 0 ";

            if (!tipAcionista.equals("T")) {
                cWhere += "AND cliente.\"tip_cliente\" = '".concat(tipAcionista).concat("' ");
            }

            if (order.equals("A")) {
                cOrder += "ORDER BY cliente.\"qde_acao\" ";
            } else {
                cOrder += "ORDER BY cliente.\"nom_cliente\" ";
            }

            if (orderTipo.equals("A")) {
                cOrder = cOrder.concat(" ASC ");
            } else {
                cOrder = cOrder.concat(" DESC ");
            }
        } else if (cTipRel.equals("transferenciaSimplificada")) {
            selectedCertificadoCheck = (RelatorioCertificadoTemp[]) session.getAttribute("tabAcionistas");
            selectedTipoTransferencia = (TipoTransferencia) session.getAttribute("tipoTransf");
            order = (String) session.getAttribute("order");

            if (selectedCertificadoCheck != null) {
                relatorio = caminho.concat("relatorioTransferenciaSimplificada.jasper");
                cWhere = " where ";
                String cCondicao1 = " cautela.id_cliente in (";
                //String cCondicao2 = " cliente_cessionario.id_cliente  in (";
                String cCondicao3 = "";

                for (int i = 0; i < selectedCertificadoCheck.length; i++) {
                    selectedCertificadoTemp = selectedCertificadoCheck[i];

                    cCondicao1 = cCondicao1.concat(selectedCertificadoTemp.getIdCliente().toString().concat(","));
                    //cCondicao2 = cCondicao2.concat(selectedCertificadoTemp.getIdCliente().toString().concat(","));
                }
                cCondicao1 = cCondicao1.concat("0) ");
                //cCondicao2 = cCondicao2.concat("0) ) ");

                cWhere = cWhere.concat(cCondicao1);

                if (selectedTipoTransferencia != null) {
                    if (selectedTipoTransferencia.getIdTipo() != 12) {
                        cCondicao3 = " and cautela.id_tipo = " + selectedTipoTransferencia.getIdTipo();
                        cWhere = cWhere.concat(cCondicao3);
                    }
                }

                if (order.equals("R")) {
                    cOrder += "ORDER BY cliente.\"nom_cliente\" ";
                } else if (order.equals("D")) {
                    cOrder += "ORDER BY cautela.\"dat_cautela\" ";
                } else if (order.equals("T")) {
                    cOrder += "ORDER BY cautela.\"id_tipo\" ";
                }
            }
        } else if (cTipRel.equals("vendas")) {
            relatorio = caminho.concat("relatorio_venda.jasper");

            selectedCautela = (Cautela) session.getAttribute("cautela");
            impPartic = (String) session.getAttribute("impPartic");
            impProposta = (String) session.getAttribute("impProposta");
            impObs = (String) session.getAttribute("impObs");
            String cDat = funcoes.ConverteDateString(selectedCautela.getDatCautela());

            cWhere = "WHERE cautela.\"id_cliente\" = ".concat(selectedCautela.getIdCliente().getIdCliente().toString()).concat(" and  cautela.\"dat_cautela\" = ").concat("'").concat(cDat).concat("'");

            parametros.put("IMPRIME_PARTIC", impPartic);
            parametros.put("IMPRIME_PROPOSTA", impProposta);
            parametros.put("IMPRIME_OBS", impObs);
        }


        //String arquivo = context.getRealPath(relatorio);
        String dirsub = context.getRealPath(caminho);

        Conecta conecta = new Conecta();

        JRAbstractLRUVirtualizer virtualizer = new JRGzipVirtualizer(100);

        InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream(relatorio);

        try {
            if (!cWhere.isEmpty()) {
                parametros.put("PAR_WHERE", cWhere);
            }
            if (!cOrder.isEmpty()) {
                parametros.put("PAR_ORDER", cOrder);
            }
            String rootDir = context.getContextPath().concat("/images/logo_SA_1.jpg");
            parametros.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
            parametros.put("SUBREPORT_DIR", dirsub.concat(File.separator));
            parametros.put("LOGO", dirsub.concat("\\logo_SA_1.jpg"));
            parametros.put("REPORT_LOCALE", new Locale("pt", "BR")); 

            //para gerar o relatório em PDF
            // o método runReportToPdfStream foi usado
            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parametros, conecta.Conecta());

            // envia o relatório em formato PDF para o browser
            response.setContentType("application/pdf");

        } catch (SQLException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } catch (JRException e) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            response.getOutputStream().print(stringWriter.toString());
        } finally {
            servletOutputStream.flush();
            servletOutputStream.close();
            reportStream.close();
            try {
                conecta.close();
            } catch (SQLException ex) {
                Logger.getLogger(ReportUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
            /*
             * session.removeAttribute("tabAcionistas");
             * session.removeAttribute("tabAcionistas");
             * session.removeAttribute("tipoTransf");
             * session.removeAttribute("cautela");
             * session.removeAttribute("impPartic");
             * session.removeAttribute("impProposta");
             * session.removeAttribute("impObs");
             *
             */
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
